const wsConfig = require('../config/ws');
const Message = require('../models/message');

class MessageHandler {
  /**
   * 处理聊天消息
   * @param {Object} message - 聊天消息对象
   * @param {Object} sender - 发送者信息
   * @returns {Promise<Object>} - 处理后的消息
   */
  static async handleChatMessage(message, sender) {
    try {
      // 验证消息内容
      if (!message.content || message.content.trim().length === 0) {
        throw new Error('消息内容不能为空');
      }

      // 构建消息对象
      const newMessage = new Message({
        senderId: sender._id,
        senderType: sender.__t || 'User',
        receiverId: message.receiverId,
        receiverType: message.receiverType || 'User',
        content: message.content,
        type: 'text'
      });

      // 保存到数据库
      await newMessage.save();

      // 构建响应消息
      return {
        id: newMessage._id,
        type: wsConfig.messageTypes.CHAT,
        senderId: sender._id,
        senderName: sender.name,
        receiverId: message.receiverId,
        content: message.content,
        timestamp: newMessage.createdAt,
        status: 'delivered'
      };
    } catch (error) {
      console.error('处理聊天消息失败:', error);
      throw error;
    }
  }

  /**
   * 处理系统通知
   * @param {Object} notification - 通知对象
   * @returns {Promise<Object>} - 处理后的通知
   */
  static async handleSystemNotification(notification) {
    try {
      // 构建通知消息
      return {
        type: wsConfig.messageTypes.SYSTEM,
        title: notification.title || '系统通知',
        content: notification.content,
        data: notification.data,
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      console.error('处理系统通知失败:', error);
      throw error;
    }
  }

  /**
   * 处理用户通知
   * @param {Object} notification - 通知对象
   * @param {Object} sender - 发送者信息
   * @returns {Promise<Object>} - 处理后的通知
   */
  static async handleUserNotification(notification, sender) {
    try {
      // 构建通知消息
      const newNotification = {
        type: wsConfig.messageTypes.NOTIFICATION,
        senderId: sender._id,
        senderName: sender.name,
        content: notification.content,
        data: notification.data,
        timestamp: new Date().toISOString()
      };

      // 如果需要，可以保存通知到数据库
      if (notification.saveToDb) {
        const savedNotification = new Message({
          senderId: sender._id,
          senderType: sender.__t || 'User',
          receiverId: notification.receiverId,
          receiverType: notification.receiverType || 'User',
          content: notification.content,
          type: 'notification',
          metadata: notification.data
        });
        
        await savedNotification.save();
        newNotification.id = savedNotification._id;
      }

      return newNotification;
    } catch (error) {
      console.error('处理用户通知失败:', error);
      throw error;
    }
  }

  /**
   * 格式化错误消息
   * @param {Error} error - 错误对象
   * @returns {Object} - 格式化的错误消息
   */
  static formatErrorMessage(error) {
    return {
      type: wsConfig.messageTypes.SYSTEM,
      content: error.message || '发生错误',
      error: true,
      timestamp: new Date().toISOString()
    };
  }

  /**
   * 验证消息格式
   * @param {Object} message - 要验证的消息
   * @param {string} messageType - 消息类型
   * @returns {Object} - 验证结果
   */
  static validateMessage(message, messageType) {
    const errors = [];

    switch (messageType) {
      case wsConfig.messageTypes.CHAT:
        if (!message.receiverId) {
          errors.push('接收者ID不能为空');
        }
        if (!message.content || message.content.length > 1000) {
          errors.push('消息内容不能为空且不能超过1000字符');
        }
        break;

      case wsConfig.messageTypes.NOTIFICATION:
        if (!message.content) {
          errors.push('通知内容不能为空');
        }
        break;

      default:
        errors.push('不支持的消息类型');
    }

    return {
      isValid: errors.length === 0,
      errors
    };
  }
}

module.exports = MessageHandler;